package cn.oi.book.pro.controller;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {

    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Object>> upload(@RequestParam("file") MultipartFile file) throws IOException {
        Map<String, Object> result = new HashMap<>();
        if (file == null || file.isEmpty()) {
            result.put("errno", 1);
            result.put("message", "文件为空");
            return ResponseEntity.badRequest().body(result);
        }
        // Basic validations
        if (file.getSize() > 10 * 1024 * 1024) { // 10MB
            result.put("errno", 1);
            result.put("message", "图片大小不能超过10MB");
            return ResponseEntity.badRequest().body(result);
        }
        String contentType = file.getContentType() == null ? "" : file.getContentType();
        if (!contentType.startsWith("image/")) {
            result.put("errno", 1);
            result.put("message", "仅支持图片类型上传");
            return ResponseEntity.badRequest().body(result);
        }
        // 目录：uploads/yyyy/MM/
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
        Path uploadRoot = Paths.get("uploads");
        Path dir = uploadRoot.resolve(datePath);
        Files.createDirectories(dir);

        String original = StringUtils.cleanPath(file.getOriginalFilename() == null ? "" : file.getOriginalFilename());
        String ext = original.contains(".") ? original.substring(original.lastIndexOf('.')) : "";
        String filename = UUID.randomUUID().toString().replace("-", "") + ext;
        Path target = dir.resolve(filename);
        try {
            Files.copy(file.getInputStream(), target, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            result.put("errno", 1);
            result.put("message", "保存文件失败");
            return ResponseEntity.internalServerError().body(result);
        }

        String url = "/uploads/" + datePath + "/" + filename;
        // wangEditor 需要 { errno:0, data:{ url: '...' } }
        result.put("errno", 0);
        Map<String, Object> data = new HashMap<>();
        data.put("url", url);
        result.put("data", data);
        return ResponseEntity.ok(result);
    }
}
